import { Mongoose, Connection } from 'mongoose';

// eslint-disable-next-line @typescript-eslint/no-var-requires
const mongoose: Mongoose = require('mongoose');

export let dataBase: Connection = null;

export const Schema = mongoose.Schema;

const SomeModelSchema = new Schema({
  name: String,
  time: Date,
});

const siteSchema = new Schema({
  name: String,
  binary: Buffer,
  living: Boolean,
  updated: { type: Date, default: Date.now },
  age: { type: Number, min: 18, max: 65, required: true },
  mixed: Schema.Types.Mixed,
  _someId: Schema.Types.ObjectId,
  array: [],
  ofString: [String], // 其他类型也可使用数组
  nested: { stuff: { type: String, lowercase: true, trim: true } },
});

export async function initMongoDB() {
  // 设置默认 mongoose 连接
  const mongoDB = 'mongodb://127.0.0.1/CSC';
  await mongoose.connect(mongoDB, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useFindAndModify: false,
    useCreateIndex: true,
  });

  // 让 mongoose 使用全局 Promise 库
  mongoose.Promise = global.Promise;
  // 取得默认连接
  dataBase = mongoose.connection;

  // 将连接与错误事件绑定 (以获得连接错误的提示)
  dataBase.on('error', console.error.bind(console, 'MongoDB 连接错误: '));

  const SomeModel = dataBase.model('SomeModel', SomeModelSchema);

  const site = dataBase.model('site', siteSchema);

  const athletes = await SomeModel.findOne({ name: 'momo' });

  console.log('SomeModel', athletes);

  const momo = new SomeModel({ name: 'momo', time: +new Date() });
}
